package api

import (
	"context"
	"strings"
	"time"

	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/backend/model"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/internal/utils/errorhandler"
	"mall/service/backend/rpc/types/backend"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateApiLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateApiLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateApiLogic {
	return &CreateApiLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// API management
func (l *CreateApiLogic) CreateApi(in *backend.ApiInfo) (*backend.BaseIDResp, error) {
	var api model.SysAPI
	if in.Path != nil {
		api.Path = strings.TrimSpace(*in.Path)

		if len(api.Path) == 0 {
			return nil, errorx.NewInvalidArgumentError("api.pathRequired")
		}

		filterMap := make(map[string]map[string][]any)
		filterMap[model.SysAPIColumns.Path] = map[string][]any{
			"equalTo": []any{api.Path},
		}
		_, count, err := l.svcCtx.SysApi.GetList(l.ctx, model.M{}, 0, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if count > 0 {
			return nil, errorx.NewAlreadyExistsError("api.pathAlreadyExists")
		}
	}
	if in.Description != nil {
		api.Description = strings.TrimSpace(*in.Description)
	}
	if in.Group != nil {
		api.APIGroup = strings.TrimSpace(*in.Group)
	}
	if in.Method != nil {
		api.Method = strings.ToUpper(strings.TrimSpace(*in.Method))
	}
	if in.Required != nil {
		api.IsRequired = uint8(*in.Required)
	}
	if in.Status != nil {
		api.Status = uint8(*in.Status)
	}
	api.CreatedAt = time.Now()
	api.UpdatedAt = time.Now()
	err := l.svcCtx.SysApi.Insert(l.ctx, nil, &api)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	return &backend.BaseIDResp{
		Id:  api.ID,
		Msg: i18n.CreateSuccess,
	}, nil
}
